package com.hefan.user.service;

import com.alibaba.fastjson.JSONObject;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hefan.common.util.MapUtils;
import com.hefan.notify.bean.PubParams;
import com.hefan.notify.itf.UmengPushService;
import com.hefan.user.bean.FriendsRecommend;
import com.hefan.user.bean.WebUser;
import com.hefan.user.config.UserConfigCenter;
import com.hefan.user.dao.FriendsRecommendDao;
import com.hefan.user.itf.WatchRecommendCacheService;
import com.hefan.user.itf.WebUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 推荐关注相关操作
 * Created by kevin_zhang on 17/03/2017.
 */
@Component("watchRecommendCacheService")
public class WatchRecommendCacheServiceImpl implements WatchRecommendCacheService {
    public static Logger logger = LoggerFactory.getLogger(WatchRecommendCacheServiceImpl.class);

    @Resource
    UserConfigCenter userConfigCenter;

    @Resource
    private JedisService jedisService;

    @Resource
    private WebUserService webUserService;

    @Resource
    private UmengPushService umengPushService;

    @Resource
    private FriendsRecommendDao friendsRecommendDao;

    //热门推荐主播id列表redis key
    private static final String hotRecommendUserIdSetRedisKey = "hotRecommendUserIdSet";
    //最新的数据修改时间 key
    private static final String hotRecommendlastUpdateTimeRedisKey = "hotRecommendlastUpdateTime";
    //热门推荐主播详细信息hash key
    private static final String hotRecommendUserInfoRedisKey = "hotRecommendUserInfo";
    /**
     * 获取热门推荐数据
     * @return
     */
    @Override
    public ResultBean getHotRecommend() {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        try {
            List<Map<String,Object>> resultList = getHotRecommendInfo();
            resultBean.setData(resultList);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取热门推荐失败");
            resultBean.setResult(ResultCode.UNSUCCESS);
            resultBean.setData(e.getMessage());
        }finally {
            return resultBean;
        }
    }

    /**
     * 初始化热门推荐
     * @return
     */
    @Override
    public ResultBean initHotRecommend() {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        try {
            logger.info("查询所有热门推荐的用户id集合");
            List<FriendsRecommend> friendsRecommendList = friendsRecommendDao.selectAllFriendsRecommend();
            logger.info("删除所有之前的数据");
            jedisService.del(hotRecommendlastUpdateTimeRedisKey);
            jedisService.del(hotRecommendUserIdSetRedisKey);
            jedisService.del(hotRecommendUserInfoRedisKey);
            logger.info("热门推荐用户redis初始化");
            dealHotRecommend(friendsRecommendList);
            logger.info("初始化将最新的数据时间设置为0L");
            //最新记录时间
            long lastUpdateTime = friendsRecommendDao.selectLastUpdateTime();
            jedisService.set(hotRecommendlastUpdateTimeRedisKey,lastUpdateTime);
        }catch (Exception e){
            resultBean.setResult(ResultCode.UNSUCCESS);
            resultBean.setData(e.getMessage());
            e.printStackTrace();
            logger.error("热门推荐用户初始化异常");
        }finally {
            return  resultBean;
        }
    }

    /**
     * 定时更新的热门推荐并发推送给前端
     *
     * @return
     */
    @Override
    public ResultBean updateLastHotRecommend() {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        long lastTime = getHotRecommendLastTime();
        if(lastTime==-1L){
            resultBean.setResult(ResultCode.UNSUCCESS);
            resultBean.setData("最新更新时间为空");
            return resultBean;
        }
        try {
            List<FriendsRecommend> friendsRecommendList =  friendsRecommendDao.selectNewFriendsRecommend( new Date(lastTime));
            if(friendsRecommendList!=null && friendsRecommendList.size()>0){
                dealHotRecommend(friendsRecommendList);
                //最新记录时间
                long lastUpdateTime = friendsRecommendList.get(0).getUpdateTime().getTime();
                jedisService.set(hotRecommendlastUpdateTimeRedisKey,lastUpdateTime);
                pushHotRecommend();
                resultBean.setData("更新了最新的热门推荐数据");
            }else{
                resultBean.setData("没有最新的热门推荐数据");
            }
        } catch (Exception e) {
            resultBean.setResult(ResultCode.UNSUCCESS);
            resultBean.setData(e.getMessage());
            e.printStackTrace();
        }finally {
            return resultBean;
        }
    }

    /**
     *全量更新热门推荐数据
     */
    @Override
    public ResultBean allUpdateHotRecommend() {
        return initHotRecommend();
    }

    @Override
    public ResultBean pushHotRecommend(){
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        PubParams params = new PubParams();
        params.setText("热门推荐好友更新啦，快来看看TA们都是谁>>");
        params.setTitle("盒饭Live");
        params.setTicker("盒饭Live");
        params.setUpType(2);
        if(!umengPushService.sendBroadcast(params)){
            resultBean.setResult(ResultCode.UNSUCCESS);
            logger.info("推送失败");
            resultBean.setData("推送失败");
        }
        return resultBean;
    }

    /**
     * 移除热门推荐 0L 失败 1L成功
     * @return
     */
    private long removeHotRecommend(){
        try {
           return RedisHelper.del(jedisService,hotRecommendUserIdSetRedisKey);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 获取最新的热门推荐的更新时间
     * @return
     */
    private long getHotRecommendLastTime(){
        try {
           return (long)jedisService.get(hotRecommendlastUpdateTimeRedisKey);
        } catch (Exception e) {
            e.printStackTrace();
            return -1L;
        }
    }
    /**
     * 处理热门推荐sortSet【包含新增、删除、更新操作】
     * @param friendsRecommendList
     * @throws Exception
     */
    private void dealHotRecommend(List<FriendsRecommend> friendsRecommendList) throws Exception {
        if(friendsRecommendList!=null && friendsRecommendList.size()>0){
            logger.info("热门推荐用户按排序插入、更新或删除 如果删除状态为1则删掉数据 否则直接覆盖");
            String userId = "";
            for(FriendsRecommend friendsRecommend:friendsRecommendList){
                //如果在推荐表中已经被删除则移除member hash中也移除该元素 其他执行更新
                if(friendsRecommend.getIsDel()==0){
                    userId = friendsRecommend.getUserId();
                    int sort = friendsRecommend.getSort();
                    //如果此用户为置顶用户    置顶时排序规则还是明星>片场>网红
                    if(sort==0){
                        //明星
                        if(friendsRecommend.getUserType()==2){
                            sort = -3;
                        }
                        //片场
                        else if(friendsRecommend.getUserType()==3){
                            sort = -2;
                        }
                        //网红
                        else if(friendsRecommend.getUserType()==1){
                            sort = -1;
                        }
                    }
                    jedisService.zadd(hotRecommendUserIdSetRedisKey,sort,userId);
                    updateRecommendInfo(userId);
                }else{
                    jedisService.hdel(hotRecommendUserInfoRedisKey,userId);
                    jedisService.zrem(hotRecommendUserIdSetRedisKey,friendsRecommend.getUserId());
                }
            }
        }
    }

    /**
     * 获取推荐的用户信息
     * @param userId
     * @return
     */
    private Map<String,Object> getUserDetailInfo(String userId){
        WebUser webUser = webUserService.findUserInfoFromCache(userId);
        if(isState(webUser)){
            return null;
        }
        Map<String,Object> map = Maps.newHashMap();
        if(webUser!=null){
            map.put("userId", userId);
            map.put("nickName",webUser.getNickName());
            map.put("personalSignature", webUser.getPersonSign());
            map.put("headImg", webUser.getHeadImg());
            map.put("sex", webUser.getSex());
            map.put("userType",webUser.getUserType());
            map.put("userLevel", webUser.getUserLevel());
        }
        return map;
    }

    /**
     * 是否冻结
     * @param webUser
     * @return
     */
    private boolean isState(WebUser webUser){
        boolean flag = false;
        if(webUser==null){
            flag =  true;
        }else{
            if(webUser.getState()==1 || webUser.getContractState()==1
                    ||webUser.getIsDel()==1 || webUser.getSuperiorState()==1
                    ){
                flag =  true;
            }
        }
        return flag;
    }

    /**
     *根据sortSet中的顺序去Hash中拼接推荐信息
     */
    private List<Map<String,Object>> getHotRecommendInfo() throws Exception {
        List<Map<String,Object>> userInfoList = Lists.newArrayList();
        //按score从小到大取出来  0 :置顶 1:明星2:片场3:网红4:普通用户
        List<Object> userIdlist = jedisService.zrange(hotRecommendUserIdSetRedisKey,0,-1);
        String userId = "";
        for(Object obj:userIdlist){
            userId = obj.toString();
            String userInfoStr = jedisService.hgetStr(hotRecommendUserInfoRedisKey,userId);
            Map<String,Object> userInfoMap =  JSONObject.parseObject(userInfoStr,Map.class);
            if(MapUtils.isEmpty(userInfoMap)){
                logger.info("redisHash中没有该条数据的信息======"+userId);
                //jedisService.zrem(hotRecommendUserIdSetRedisKey,userId);
                continue;
            }
            userInfoList.add(userInfoMap);
        }
        return userInfoList;
    }

    /**
     * 根据userid更新hash
     * @param userId
     */
    private void updateRecommendInfo(String userId) throws Exception {
        Map<String,Object> userDetailInfomap = getUserDetailInfo(userId);
        //如果用户信息不存在则删除推荐列表中的信息
        if(MapUtils.isEmpty(userDetailInfomap)){
            logger.info("推荐用户信息不存在用户id=="+userId);
            logger.info("删除推荐列表中的用户id");
            jedisService.zrem(hotRecommendUserIdSetRedisKey,userId);
        }else{
            logger.info("推荐用户信息更新"+userId);
            logger.info("像hash中添加key为userId value为"+JSONObject.toJSONString(userDetailInfomap));
            jedisService.hset(hotRecommendUserInfoRedisKey,userId, JSONObject.toJSONString(userDetailInfomap));
        }
    }
}
